package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.util.BeanHelper;
import com.heima.common.util.JwtUtils;
import com.heima.model.user.dtos.AppLoginDto;
import com.heima.model.user.dtos.UserInfoDto;
import com.heima.user.entity.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author HM
 * @since 2022-04-27
 */
@Slf4j
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    @Autowired
    private BCryptPasswordEncoder encoder;
    /**
     * 用户登录
     * @param dto
     * @return
     */
    @Override
    public Map<String, Object> login(AppLoginDto dto) {
        Map<String, Object> result = new HashMap<>();
        Integer userId = 0;
//        判断是否手机号密码登录
        if(StringUtils.isNotBlank(dto.getPhone()) &&
                StringUtils.isNotBlank(dto.getPassword())){
//            根据用户手机号查询用户信息
            LambdaQueryWrapper<ApUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ApUser::getPhone,dto.getPhone());
            ApUser apUser = getOne(queryWrapper);
            if(apUser == null){
                log.error("用户不存在，phone={}",dto.getPhone());
                throw new LeadException(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
            }
//            验证密码
            boolean b = encoder.matches(dto.getPassword(), apUser.getPassword());
            if(!b){
                log.error("密码不正确");
                throw new LeadException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
//            给userId赋值
            userId = apUser.getId();
            result.put("user", BeanHelper.copyProperties(apUser, UserInfoDto.class));
        }else{
//            不能录先看看，没有用户信息
            if(StringUtils.isBlank(dto.getEquipmentId())){
                log.error("参数不正确");
                throw new LeadException(AppHttpCodeEnum.PARAM_REQUIRE);

            }
        }
//        生成token
        String token = JwtUtils.generateTokenExpireInMinutes(userId, 120);
        result.put("token",token);
        return result;
    }
}
